<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/3/21
 * Time: 15:17
 */

namespace app\index\domain;

use app\bbs\api\FilterKeyWordsApi;
use app\bbs\api\ForumAttachmentApi;
use app\bbs\api\ForumForumApi;
use app\bbs\api\ForumPostApi;
use app\bbs\api\ForumSilentApi;
use app\bbs\api\ForumPostcommentApi;
use app\bbs\api\ForumThreadApi;
use app\bbs\api\VPostAndCommentApi;
use app\bbs\api\ForumUserAdmingroupApi;
use app\bbs\model\ForumAdmingroup;
use app\bbs\model\ForumPost;
use app\system\api\MemberApi;
use app\system\api\UserLogApi;
use app\admin\api\MessageApi;
use app\admin\model\Message;
use app\bbs\api\BbsMemberApi;

class ForumPostDomain extends BaseDomain{
    protected $business_code = 'forumpost';

    /**
     * 同级 回复品论 - 分页
     */
    public function postBBL(){
        $this->checkVersion($this->api_ver);
        addLog("ForumPost/postBBL",$_GET,$_POST,"应用" . $this->client_id . "调用同级回评查询接口");
        if(IS_POST){
            $tid      = $this->_post('tid','','tid缺失');
            $curpage  = $this->_post('page_no',1);
            $pagesize = $this->_post('page_size',10);
            // $fid = 1 ;//4
            // $r = apiCall(ForumPostApi::QUERY_WITH_COMMENT,[['tid'=>$tid,'fid'=>$fid],['curpage'=>$curpage,'size'=>$pagesize],'dateline desc']);
            $r = apiCall(VPostAndCommentApi::QUERY,[['tid'=>$tid],['curpage'=>$curpage,'size'=>$pagesize],'dateline asc']);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            // $time = time() - $val['dateline'];
            // $val['dateline_show'] = $this->getDateInfo($time,$val['dateline']);
            if(!empty($r['info']['list'])){
                foreach ($r['info']['list'] as &$v) {
                    $uid = intval($v['author_id']);
                    //查询用户信息
                    $userInfo = $this->getUserInfo2($uid);
                    $v['author'] = empty($userInfo) ? '' : $userInfo['nickname'];
                    $v['head'] = empty($userInfo) ? '' : $userInfo['head'];
                    $v['sex'] = empty($userInfo) ? '' : $userInfo['sex'];
                    $uid = intval($v['to_uid']);
                    $v['to_uinfo'] = ['temp'=>'']; //安卓占位符
                    if($uid){
                        $userInfo = $this->getUserInfo2($uid);
                        $v['to_uinfo']['nickname'] =  empty($userInfo) ? '' : $userInfo['nickname'];
                        $v['to_uinfo']['head'] =  empty($userInfo) ? '' : $userInfo['head'];
                        $v['to_uinfo']['sex'] =  empty($userInfo) ? '' : $userInfo['sex'];
                    }
                }
            }
            $this->apiReturnSuc($r['info']);
        }
    }
    /**
     * 回复分页查询
     */
    public function query(){
        $this->checkVersion($this->api_ver);
        addLog("ForumPost/query",$_GET,$_POST,"应用" . $this->client_id . "调用回复查询接口");

        if(IS_POST){

            $fid        = $this->_post('fid','');
            $tid        = $this->_post('tid','','主题ID缺失');
            // $typeid  = $this->_post('typeid',0);
            $curpage    = $this->_post('page_no',1);
            $pagesize   = $this->_post('page_size',10);
            $maxcomment = $this->_post('max_comment',2);
            $all_reply  = $this->_post('all_reply',0);
            $order      = $this->_post('order',0);
            $view_inc   = 1;//$this->_post('view_inc',0);
            if(1===intval($all_reply)) $all_reply = true;
            else $all_reply = false;
            if($fid === ''){
                $r = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid]]);
                if($r['status']){
                    if(empty($r['info']))  $this -> apiReturnSuc($r['info']);
                    $fid = $r['info']['fid'];
                }else{
                    $this -> apiReturnErr($r['info']);
                }
            }
            if($order) $order = 'dateline desc';
            else $order = 'dateline asc';
            $r = apiCall(ForumPostApi::QUERY_POST,[$fid,$tid,$curpage,$pagesize,$maxcomment,$view_inc,$all_reply,$order]);
            if($r['status']){
                $this->apiReturnSuc($r['info']);
            }else{
                $this->apiReturnErr($r['info']);
            }


        }else{
            $this->apiReturnErr('只支持POST请求');
        }

    }

    /**
     * 回复详情
     */
    public function detail(){

        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("ForumPost/detail",$_GET,$_POST,"应用" . $this->client_id . "调用帖子详情接口");

            $fid = $this->_post('fid','','论坛ID缺失');
            $tid = $this->_post('tid','','主题ID缺失');
            $pid = $this->_post('pid','','帖子ID缺失');

            $result = apiCall(ForumPostApi::DETAIL_POST,[$fid,$tid,$pid]);
            if($result['status']){
                $this->apiReturnSuc($result['info']);
            }else{
                $this->apiReturnErr($result['info']);
            }


        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }

    /**
     * 评论分页查询
     */
    public function commentQuery(){
        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("ForumPost/commentQuery",$_GET,$_POST,"应用" . $this->client_id . "调用评论查询接口");

            $tid = $this->_post('tid','','主题ID缺失');
            $pid = $this->_post('pid','','帖子ID缺失');
            $curpage  = $this->_post('page_no',1);
            $pagesize = $this->_post('page_size',10);

            $result = apiCall(ForumPostApi::QUERY_COMMENT,array($tid,$pid,$curpage,$pagesize));
            if($result['status']){
                $this->apiReturnSuc($result['info']);
            }else{
                $this->apiReturnErr($result['info']);
            }
        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }

    /**
     * 回复
     */
    public function reply(){
        if(IS_POST){
            $this->checkVersion(101);
            addLog("ForumPost/reply",$_GET,$_POST,"应用" . $this->client_id . "调用主题回帖接口");

            $fid         = $this->_post('fid','','板块ID缺失');
            $tid         = $this->_post('tid','','帖子ID缺失');
            // $author      = $this->_post('author','','作者缺失');
            $author_id   = $this->_post('author_id','','作者ID缺失');
            // $subject     = $this->_post('subject','','帖子标题缺失');
            $message     = $this->_post('message','','回帖内容缺失');
            $attachments = $this->_post('attachments','');
            //回帖间隔判断
            $r = getCacheTree('POST_AND_COMMENT_REST',3);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $rest = intval($r['info']);
            unset($r);
            $cacheKey = 'postcommentrest-'.$author_id;
            if(S($cacheKey)){
                $this->apiReturnErr('请保持间隔'.$rest.'秒');
            }
            //板块验证
            $result  = apiCall(ForumForumApi::GET_INFO,[['fid'=>$fid]]);
            if(!$result['status']) $this -> apiReturnErr($result['info']);
            if(empty($result['info'])) $this->apiReturnErr('非法板块');

            $check = $result['info']['modnewposts'];
            $status= intval($result['info']['status']);
            if(1 === $status) $this->apiReturnErr('该板块已被锁定!');
            if(-1 === $status) $this->apiReturnErr('该板块已被关闭!');
            $fup = intval($result['info']['fup']);
            if($fup){
                //验证父板块
                $result  = apiCall(ForumForumApi::GET_INFO,[['fid'=>$fup]]);
                if(!$result['status'] || empty($result['info']))
                    $this->apiReturnErr('服务器故障：forum forum getOne');
                // $fcheck = $result['info']['modnewposts'];
                $fstatus = intval($result['info']['status']);
                if(1 === $fstatus) $this->apiReturnErr('父板块已被锁定!');
                if(-1 === $fstatus) $this->apiReturnErr('父板块已被关闭!');
            }
            //验证用户信息
            $res = apiCall(MemberApi::GET_INFO,[['uid'=>$author_id]]);
            if(false === $res['status']) $this -> apiReturnErr('系统故障: get member');
            if(empty($res['info'])) $this -> apiReturnErr('非法用户');
            // if($res['info']['nickname'] != $author){
            //     $this -> apiReturnErr("信息未及时更新，请重新登录后尝试！");
            // }
            //用户是否禁言
            $this->checkSilent($author_id);
            // ======================================================
            //关键词过滤
            // $subject = $this->filter($subject);
            $message = $this->filter($message);
            // $ip      = get_client_ip();
            $now     = NOW_TIME;
            // $status  = (1==$check || (isset($fcheck) && 1==$fcheck))?1:0; //该板块及父板块是否开启审核，
            $status  = (1==$check)?1:0; //该板块是否开启审核，

            //查询帖子信息
            $result = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid,'fid'=>$fid]]);
            if(!$result['status']) $this->apiReturnErr($result['info']);
            if(empty($result['info'])) $this->apiReturnErr('fid或tid错误');
            $subject = $result['info']['subject'];
            $thread_uid = $result['info']['author_id'];
            $result = apiCall(ForumPostApi::REPLY,array($fid,$tid,$author_id,$message,$attachments));
            if(!$result['status']) $this->apiReturnErr($result['info']);
            S($cacheKey,1,$rest);
            //发帖者 奖励
            $r = apiCall(UserLogApi::POST_ME,[$thread_uid]);
            if(!$r['status'])  $this ->apiReturnErr($r['info']);

            //回帖者 奖励
            $r = apiCall(UserLogApi::POST_ADD,[$author_id]);
            if(!$r['status'])  $this ->apiReturnErr($r['info']);
            $arr = $r['info'];
            if(1 == $check){
                //需要审核
                $msg = '回帖成功，等待审核';
            }else{
                // 推送消息 - 新回复
                $entity = [
                    'from_id' =>0,
                    'title'   =>Message::MESSAGE_BBS,
                    'content' =>'您的帖子('.($subject ? $subject:$fid).')现有一条新的评论',
                    'summary' =>'您的帖子('.($subject ? $subject:$fid).')发现新评论',
                    'extra'   =>'', //消息记录中的
                ];
                $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_BBS_ACTIVITY,'extra'=>['type'=>0]]; //推送参数
                $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_BBS,$entity,$thread_uid,false,$after_open]);
                if(!$r['status']) $this->apiReturnSuc($r['info']);
                $msg = '回帖成功';
            }
            $this->apiReturnSuc(['info'=>$msg,'msg'=>$arr,'pid'=>$result['info']]);

        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }

    /**
     * 删除回复
     */
    public function delete(){
        if(IS_POST){
            $this->checkVersion(101);
            addLog("ForumPost/Delete",$_GET,$_POST,"应用" . $this->client_id . "调用删除自己回复接口");

            $uid = $this->_post('uid','','用户ID缺失');
            $fid = $this->_post('fid','','论坛板块ID缺失');
            $tid = $this->_post('tid','','帖子ID缺失');
            $pid = $this->_post('pid','','回复ID缺失');

            $result = apiCall(ForumPostApi::DELETE_POST,array($uid,$fid,$tid,$pid));
            if($result['status']){
               //-score -exp
               $r = apiCall(UserLogApi::POST_DELETE,[$uid]);
               if(!$r['status']) $this->apiReturnErr($r['info']);
               $this->apiReturnSuc(['info'=>$result['info'],'msg'=>$r['info']]);
            }else{
               $this->apiReturnErr($result['info']);
            }

        }else{
            $this->apiReturnErr('只支持POST请求');
        }

    }


    /**
     * 删除评论
     */
    public function deleteComment(){

        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("ForumPost/userDeleteComment",$_GET,$_POST,"应用" . $this->client_id . "调用删除自己评论接口");

            $uid = $this->_post('uid','','用户ID缺失');
            $tid = $this->_post('tid','','主题ID缺失');
            $pid = $this->_post('pid','','帖子ID缺失');
            $id  = $this->_post('cid','','评论ID缺失');

            $result = apiCall(ForumPostApi::DELETE_COMMENT,array($uid,$tid,$pid,$id));
            if($result['status']){
                $this->apiReturnSuc($result['info']);
            }else{
                $this->apiReturnErr($result['info']);
            }


        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }

    /**
     * 评论
     */
    public function replyPost(){

        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("ForumPost/replyPost",$_GET,$_POST,"应用" . $this->client_id . "调用回复评论接口");

            $fid       = $this->_post('fid','','板块ID缺失');
            $pid       = $this->_post('pid',0,'pid缺失');
            $tid       = $this->_post('tid','','帖子ID缺失');
            // $author    = $this->_post('author','','作者缺失');
            $author_id = $this->_post('author_id','','作者ID缺失');
            $comment   = $this->_post('comment','','评论内容不存在');//回复内容不存在
            $to_user   = $this->_post('to_uid',0);
            //评论间隔判断
            $r = getCacheTree('POST_AND_COMMENT_REST',3);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $rest = (int)$r['info'];
            unset($r);
            $cacheKey = 'postcommentrest-'.$author_id;
            if(S($cacheKey)){
                $this->apiReturnErr('请保持间隔'.$rest.'秒');
            }
            //版块验证
            $result  = apiCall(ForumForumApi::GET_INFO,[['fid'=>$fid]]);
            if(!$result['status']) $this -> apiReturnErr($result['info']);
            if(empty($result['info'])) $this->apiReturnErr('非法板块');
            $check = $result['info']['modnewposts'];
            $status= intval($result['info']['status']);
            if(1 === $status) $this->apiReturnErr('该板块已被锁定!');
            if(-1 === $status) $this->apiReturnErr('该板块已被关闭!');
            $fup = intval($result['info']['fup']);

            if($fup){
                //验证父板块
                $result  = apiCall(ForumForumApi::GET_INFO,[['fid'=>$fup]]);
                if(!$result['status'] || empty($result['info']))
                    $this->apiReturnErr('服务器故障：forum forum getOne');
                // $fcheck = $result['info']['modnewposts'];
                $fstatus= intval($result['info']['status']);
                if(1 === $fstatus) $this->apiReturnErr('父板块已被锁定!');
                if(-1 === $fstatus) $this->apiReturnErr('父板块已被关闭!');
            }
            //帖子是否存在
            $result = apiCall(ForumThreadApi::GET_INFO,array(array('tid'=>$tid)));
            if(!$result['status']) $this->apiReturnErr('系统错误： thread get!');
            if(empty($result['info'])) $this->apiReturnErr('此帖不存在!');
            // if(4 == intval($fid)){
            //     //宝宝乐
            // }else{
            if(!intval($pid)) $this->apiReturnErr('pid缺失');
            //回复是否存在
            $result = apiCall(ForumPostApi::GET_INFO,[['pid'=>$pid]]);
            if(!$result['status']) $this->apiReturnErr('系统错误： post get!');
            if(empty($result['info'])) $this->apiReturnErr('此评论不存在!');
            // }
            if(!$to_user) $to_user = $result['info']['author_id'];
            //验证用户信息
            if(intval($to_user)){
                $res = apiCall(MemberApi::GET_INFO,[['uid'=>$author_id]]);
                if(false===$res['status']) $this -> apiReturnErr($res['info']);
                if(empty($res['info'])) $this -> apiReturnErr('非法用户');
                if($to_user != $author_id){
                    $res = apiCall(MemberApi::GET_INFO,[['uid'=>$to_user]]);
                    if(false===$res['status']) $this -> apiReturnErr($res['info']);
                    if(empty($res['info'])) $this -> apiReturnErr('非法用户');
                }
                unset($res);
            }
            // if($res['info']['nickname'] != $author){
            //     $this -> apiReturnErr("信息未及时更新，请重新登录后尝试！");
            // }
            //禁言检测
            $this->checkSilent($author_id);
            //关键词过滤
            $comment = $this->filter($comment);
            //TODO toUser 是否在评论队列
            $result  = apiCall(ForumPostApi::REPLY_POST,array($pid,$tid,$author_id,$comment,$to_user));
            if($result['status']){
                S($cacheKey,'ing',$rest);
                // 推送消息
                $entity = [
                    'from_id' =>0,
                    'title'   =>Message::MESSAGE_BBS,
                    'content' =>'您的评论现有一条新的回复',//新评论
                    'summary' =>'您的评论发现新回复',//新评论
                    'extra'   =>'', //消息记录中的
                ];
                $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_BBS_ACTIVITY,'extra'=>['type'=>1]]; //推送参数
                $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_BBS,$entity,$to_user,false,$after_open]);
                if(!$r['status']) $this->apiReturnSuc($r['info']);

                $score = C('score_comment_add')?intval(C('score_comment_add')):10;
                //发布评论+10积分
                apiCall(MemberApi::RAISE_SCORE,array($author_id,$score));
                $this->apiReturnSuc($result['info']);
            }else{
                $this->apiReturnErr($result['info']);
            }

        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }

    /**
     * 关键词过滤
     */
    private function filter($posts){
        $result = apiCall(FilterKeyWordsApi::FILTER,array($posts));
        return $result['info'];
    }

    //禁言检查 start_time-end_time=禁言时间  0/永久
    private function checkSilent($uid){
        //最后一次禁言
        // $where = ['uid'=>$uid,'end_time'=>['egt',NOW_TIME];
        $where  = ' `uid`=\''.$uid.'\' and `end_time`>='.NOW_TIME;
        $result = apiCall(ForumSilentApi::GET_INFO,[$where,'start_time desc']);
        if(!$result['status']) $this -> apiReturnErr('服务器故障: silent get');
        if(empty($result['info'])) return true;
        // if($result['info']['end_time'] == $result['info']['start_time']){
            // $this -> apiReturnErr('您已被禁言：结束时间：世界末日！');
        // }else{
            $this->apiReturnErr('您已被禁言：结束时间：'.getDateDiff($result['info']['end_time']));
        // }
    }

    /**
     * 查询附件
     */
    private function queryAttachment($tid,$pid,&$arr){

        //查询附件
        $map = array(
            'pid' => $pid,
            'tid' => $tid
        );
        $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,array('aid')));
        if($result['status']){
            $arr['img'] = array();
            foreach($result['info'] as $key=>$v){
                if($key >5)break;
                array_push($arr['img'],$v['aid']);
            }

        }

    }

    /**
     * 查询指定条数评论
     */
    private function queryComments($tid,$pid,$maxcomment,&$arr){

        if($arr['comment']==1){
            $arr['view_more'] = 0;
            $map = array(
                'tid' => $tid,
                'pid' => $pid,
            );
            $order['id'] = 'desc';
            $page = array('curpage'=>0,'size'=>$maxcomment);
            $result = apiCall(ForumPostcommentApi::QUERY_WITH_COUNT,array($map,$page,'id desc'));
            if($result['status']){
                if($result['info']['count']<=$maxcomment){
                    //不需要查看更多
                }else{
                    $arr['view_more'] = 1;
                }
                $arr['comment_num'] = $result['info']['count'];
                $arr['comments'] = $result['info']['list'];

                foreach($arr['comments'] as &$val){
                    //时间转换
                    $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                    //查询用户信息
                    $this->getUserInfo($val['author_id'],$val);
                }
            }else{
                $this->apiReturnErr('获取'.$arr['pid'].'评论失败');
            }
        }

    }

    /**
     * 查询用户信息
     */
    private function getUserInfo2($uid){
        $r = apiCall(BbsMemberApi::GET_USER_INFO,[$uid,false,false,false,false]);
        // $r = apiCall(MemberApi::GET_INFO,array($uid));
        if($r['status'] && $r['info']){
            return $r['info'];
        }else{
            return [];//$this->apiReturnErr('查询用户信息失败');
        }
    }

    /**
     * 查询用户信息
     */
    private function getUserInfo($uid,&$arr){
        $r = apiCall(BbsMemberApi::GET_USER_INFO,[$uid,false,false,false,false]);
        if($r['status']){
            $arr['user_info'] = $r['info'];
        }else{
            $arr['user_info'] = [];//$this->apiReturnErr('查询用户信息失败');
        }
    }
    private  function getDateInfo($time,$dateline){

        if($time <= 60){
            return "刚刚";
        }else if($time > 60 && $time <= 3600){
            return floor($time/60)."分钟前";
        }else if($time > 3600 && $time <= 3600*24){
            return floor($time/3600)."小时前";
        }else if($time > 3600*24){
            return date('Y-m-d',$dateline);
        }

    }
}